import React, { useEffect, useRef, useState } from 'react';
import './list.less';

import { history } from 'umi';
import { ArrowLeft } from '@react-vant/icons';
export default function list() {
  const [uName, setUName] = useState(''); // input框的数据
  const [chatMessages, setChatMessages] = useState([]); // 聊天消息的状态
  const [websocket, setWebsocket] = useState(null); // WebSocket 实例的状态
  let chatContainerRef = useRef(); //监听到内容块的节点
  useEffect(() => {
    // 创建 WebSocket 连接
    const newWebsocket = new WebSocket('ws://172.20.10.2:8080');
    // WebSocket 连接建立时触发
    newWebsocket.onopen = () => {
      if (newWebsocket.readyState === 1) {
        console.log('连接成功');
      }
    };
    // WebSocket 接收到消息时触发
    newWebsocket.onmessage = (event) => {
      console.log(event);
      const chatS = JSON.parse(event.data); // 接收的数据和发送消息用户的id
      console.log(chatS);
      setChatMessages((prevMessages) => [...prevMessages, chatS]); // 通过结构赋值的方式将数据添加进去
      if (chatContainerRef.current) {
        // 用于将聊天界面滚动到最新消息的位置，以确保用户能够看到最新的消息内容
        chatContainerRef.current.scrollTop =
          chatContainerRef.current.scrollHeight;
      }
    };
    // 设置 WebSocket 实例状态
    setWebsocket(newWebsocket);
    // 当组件卸载时关闭 WebSocket 连接
    return () => {
      newWebsocket.close();
      console.log('断开连接');
    };
  }, []);
  // 处理发送消息的函数
  const handleSendMessage = () => {
    // 在发送消息之前检查 WebSocket 连接的状态，以确保连接处于打开状态，
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      const values = {
        uName: uName,
        id: id,
      };
      // 清空输入框内容
      setUName('');
      // 发送消息给 WebSocket 服务器
      websocket.send(JSON.stringify(values));
    }
  };
  let id = JSON.parse(localStorage.getItem('listid'));
  console.log(chatMessages);

  return (
    <div className="chat-app">
      <div className="chat-header">
        <div style={{ width: '42vw', marginTop: '7px' }}>
          <ArrowLeft
            style={{ fontSize: '25px' }}
            onClick={() => history.push('/sixin')}
          />
        </div>
        <div style={{ fontSize: '20px', fontWeight: '600' }}>消息</div>
      </div>
      <div style={{ height: '50px' }}></div>
      <div className="chat-main" ref={chatContainerRef}>
        {chatMessages.map((message, index) =>
          message.id == id ? (
            <div key={index} className="right">
              <div className="chat-main-text">{message.uName}</div>
              <div className="chat-main-header">
                <img
                  src="https://img.axureshop.com/8d/2f/30/8d2f3075c60b454382a8e5b016e47cf6/images/%E7%A7%81%E4%BF%A1%E6%B6%88%E6%81%AF/pic_u15089.png"
                  alt=""
                />
              </div>
            </div>
          ) : (
            <div key={index} className="left">
              <div className="chat-main-text">{message.uName}</div>
              <div className="chat-main-header">
                {' '}
                <img
                  src="https://img.axureshop.com/8d/2f/30/8d2f3075c60b454382a8e5b016e47cf6/images/%E7%A7%81%E4%BF%A1%E6%B6%88%E6%81%AF/pic_u15089.png"
                  alt=""
                />
              </div>
            </div>
          ),
        )}
      </div>
      <div style={{ height: '50px' }}></div>
      <div className="chat-input">
        <input
          type="text"
          placeholder="输入消息"
          value={uName}
          onChange={(e) => setUName(e.target.value)}
        />
        <button onClick={handleSendMessage}>发送</button>
      </div>
    </div>
  );
}
